package org.folio.rest.impl.other.config;

import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;

import javax.ws.rs.core.Response;
import java.util.Map;
import java.util.function.Function;

/**
 * @author lee
 * @Classname Config
 * @Description TODO
 * @Date 2020/6/29 18:09
 * @Created by lee
 */
public class Config implements ConfigService {


    private final Vertx vertx;

    private ConfigRetriever retriever;

    public Config(Vertx vertx) {
        this.vertx = vertx;
        this.initConfig();
    }

   public JsonObject initConfig()
   {
       ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file")
               .setFormat("json")
               .setConfig(new JsonObject().put("path", "conf.json"));
       ConfigRetrieverOptions options = new ConfigRetrieverOptions()
               .addStore(fileStore) ;


       this.retriever = ConfigRetriever.create(vertx, options);
       return this.retriever.getCachedConfig();
   }
   public ConfigRetriever getConfig(){
        return this.retriever;
   }

    @Override
    public String get(String key) {

        JsonObject value = this.retriever.getCachedConfig();
        return value.getString(key);
    }

    @Override
    public Future<Map<String, Object>> getAll() {
         Future<JsonObject> future = Future.future();
         this.retriever.getConfig(future.completer());

        return  future.map(responseMapper(Map.class)) ;
    }
    private static <T> Function<JsonObject, Map<String,Object>> responseMapper(Class<T> type) {

        return resp ->  resp.getMap();
    }
    public void getAll( Handler<AsyncResult<Map>> asyncResultHandler){

        this.retriever.getConfig(h->{
            if (h.succeeded()){
                asyncResultHandler.handle(Future.succeededFuture(h.result().getMap()));
            }else {
                asyncResultHandler.handle(Future.failedFuture(h.cause()));
            }
        });

    }
}
